package com.lh.service.impl;

import com.lh.dao.UserDao;
import com.lh.model.File;
import com.lh.model.User;
import com.lh.service.FileService;
import com.lh.service.UserService;
import com.lh.util.MyException;
import com.lh.util.MyLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author LuoHang
 * @Date 2022-05-08 19:55
 **/
@Service(value = "userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Autowired
    @Qualifier("fileServiceImpl")
    private FileService fileService;

    @Transactional(rollbackFor = Exception.class,propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public User getUserById(Integer id) {
        return id ==null ? new User() : userDao.getUserById(id);
    }

    @Transactional(rollbackFor = Exception.class,propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public User login(User user) {
        return userDao.login(user);
    }

    @Transactional(rollbackFor = MyException.class,propagation = Propagation.REQUIRED,timeout = 1000)
    @Override
    public boolean addUser(User user) {
        return userDao.addUser(user) > 0;
    }


    @Transactional(rollbackFor = MyException.class,propagation = Propagation.REQUIRED,timeout = 1000)
    @Override
    public boolean addUserException(User user) throws MyException{
        MyLog.info(UserDao.class,"=====事务测试：开始添加用户数据");
        if (userDao.addUser(user) > 0){
            MyLog.info(UserDao.class,"=====事务测试：数据库用户数据添加成功");
            MyLog.info(UserDao.class,"=====事务测试：抛出事务异常");
            throw new MyException("测试事务UserServiceImpl.addUserException()抛出的异常");
        }
        return false;
    }
    @Transactional(rollbackFor = MyException.class,propagation = Propagation.REQUIRED,timeout = 5000)
    @Override
    public User addUserAngImg(User user, File file) throws MyException{
        MyLog.info(UserDao.class,"=====事务测试：开始添加用户数据");
        //如果用户添加成功
        if (userDao.addUser(user) > 0){
            MyLog.info(UserDao.class,"=====事务测试：数据库用户数据添加成功");
            //获取用户生成的uid,插入到file对象关联
            user = userDao.login(user);
            file.setUid(user.getId());
            //添加file对象到数据库
            MyLog.info(UserDao.class,"=====事务测试：UserDao.addUserAngImg()开始添加file对象");
            fileService.addFile(file);
        }else {
            return null;
        }
        return user;
    }

    @Override
    public int deleteById(Integer id) {
        return userDao.deleteById(id);
    }
}
